package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

type CzlistRBody struct {
	Data       []models.Buyordersql `json:"data"`
	PageNo     int                  `json:"pageNo"`
	PageSize   int                  `json:"pageSize"`
	TotalCount int64                `json:"totalCount"`
	TotalPage  int64                `json:"totalPage"`
	Zprice     float64              `json:"zprice"`
}

func Czlist(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	paytime := request.Paytime
	endtime := request.Endtime
	phone := request.Phone
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Buyordersql
	var users1 []models.Buyordersql
	res := data_source.Db.Model(&models.Buyorder{}).Select("buyorder.*, user.phone, user.nickname").Joins("left join user on user.id = buyorder.uid").Where("buyorder.status = 2").Where("buyorder.price > 0")
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}
	if paytime > 0 {
		res = res.Where("buyorder.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("buyorder.addtime < ?", endtime)
	}
	res.Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("buyorder.id desc").Find(&users)
	if paytime > 0 && endtime > 0 {
		res1 := data_source.Db.Model(&models.Buyorder{}).Select("buyorder.*, user.phone, user.nickname").Joins("left join user on user.id = buyorder.uid").Where("buyorder.status = 2")
		if phone != "" {
			res1 = res1.Where("user.phone = ?", phone)
		}
		if paytime > 0 {
			res1 = res1.Where("buyorder.addtime >= ?", paytime)
		}
		if endtime > 0 {
			res1 = res1.Where("buyorder.addtime < ?", endtime)
		}
		res1.Find(&users1)
	}
	var zprice float64
	for _, v := range users1 {
		zprice = zprice + v.Price
	}
	var totalPage int64
	if count > 0 {
		mo := count % int64(pageSize)
		if mo > 0 {
			totalPage = count/int64(pageSize) + 1
		} else {
			totalPage = count / int64(pageSize)
		}
	}

	data := CzlistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
		Zprice:     zprice,
	}
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "查看充值记录",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}
